import requests
from pathlib import Path
import json
import datetime


def pprint(a):
    print('[' + datetime.datetime.now().strftime('%H:%M:%S') + '] ' + a)


def pinput(notice):
    return input('[' + datetime.datetime.now().strftime('%H:%M:%S') + '] ' +
                 notice)


print("""注意：
    本程序获取B站热门视频，并保存到json文件中
    受限于命令行的输出格式，我们仅能输出前5个视频的部分信息
    本程序会将获取结果以json的格式保存在与本程序同目录下的{日期}.json文件中
""")

url = "https://api.bilibili.com/x/web-interface/ranking/v2?type=all"
headers = {
    "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"
}

response = requests.get(url, headers=headers).json()
path = Path(f"./{datetime.datetime.now().strftime('%Y-%m-%d %H-%M')}.json")

pprint("获取成功")
save = pinput("是否仅保存前5个视频的信息？(y/n)").lower()
if save == 'n':
    path.write_text(json.dumps(response['data']['list'],
                               ensure_ascii=False,
                               indent=4),
                    encoding="utf-8")
elif save == 'y':
    path.write_text(json.dumps(response['data']['list'][:5],
                               ensure_ascii=False,
                               indent=4),
                    encoding="utf-8")
else:
    pprint("输入错误，默认保存前5个视频的信息")
    path.write_text(json.dumps(response['data']['list'][:5],
                               ensure_ascii=False,
                               indent=4),
                    encoding="utf-8")
pprint("已将获取结果保存在" + path.name + "中")
pprint('note' + response['data']['note'])
